package com.cjjd.c.wxapi;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;

import com.cjjd.c.App;
import com.cjjd.c.base.BaseActivity;
import com.cjjd.c.bean.WxLoginAccessTokenBean;
import com.cjjd.c.utils.LogUtil;
import com.cjjd.c.utils.ToastUtil;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;

import org.greenrobot.eventbus.EventBus;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * ----------------------------------
 * Created by xyd on 2017/9/20.
 * <p/>
 * 描  述：
 * <p/>
 * 修订历史:
 * ----------------------------------
 */

public class WXEntryActivity extends BaseActivity implements IWXAPIEventHandler {


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        App.WX_API.handleIntent(getIntent(), this);
    }

    @Override
    public Fragment getContentFragment() {
        return null;
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp resp) {



        LogUtil.e("xyd","wxlogin");
        LogUtil.e("xyd","errorcode = "+resp.errCode);
        // 微信登录授权返回
        switch (resp.errCode) {

            case BaseResp.ErrCode.ERR_OK:
                //拿到了微信返回的code,立马再去请求access_token
                String code = ((SendAuth.Resp) resp).code;
                Log.e("xyd", "code = " + code);
                //就在这个地方，用网络库发请求，注意是get请求
                getWxOpenId(code);
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:  // 拒绝
            case BaseResp.ErrCode.ERR_USER_CANCEL:  // 取消
                ToastUtil.showToast("取消授权登录");
                finish();
                break;

        }

    }

    private void getWxOpenId(String code) {
        Call<WxLoginAccessTokenBean> authorization_code = service.getWxAccessToken(App.APP_ID, App.AppSecret, code, "authorization_code");
        authorization_code.enqueue(new Callback<WxLoginAccessTokenBean>() {
            @Override
            public void onResponse(Call<WxLoginAccessTokenBean> call, Response<WxLoginAccessTokenBean> response) {
                if (response.isSuccess()) {
                    WxLoginAccessTokenBean wxLoginAccessTokenBean = response.body();
                    Log.e("xyd", "send loginIntent");
                    EventBus.getDefault().post(wxLoginAccessTokenBean);

                    finish();
                }
            }

            @Override
            public void onFailure(Call<WxLoginAccessTokenBean> call, Throwable t) {

            }
        });
    }

}
